from app.wtforms import UserForm, LoginUserForm
from app.models import User
from app.utils.message import to_dict_msg
from app.handlers.BaseHandler import BaseHandler
from config import JWT_SETTING
import jwt, sys, time, hashlib
from app.utils.login_require import login_require_async


class RegisterHandler(BaseHandler):
    async def post(self):
        user_form = UserForm(self.request.arguments)
        if user_form.validate():
            # 验证用户是否存在
            try:
                username = user_form.username.data
                exist_user = await self.manager.get(User, username=username)
                if exist_user:
                    self.finish(to_dict_msg(code=500, msg='手机号已注册'))
            except:
                string = user_form.password.data
                sha1 = hashlib.sha1()
                sha1.update(string.encode('utf-8'))
                password = sha1.hexdigest()
                await self.manager.create(User, username=user_form.username.data, password=password)
                self.finish(to_dict_msg(code=200, msg='注册成功'))
        else:
            self.finish(to_dict_msg(code=500, msg='注册失败', **user_form.errors))


class LoginHandler(BaseHandler):
    async def post(self):
        user_form = LoginUserForm(self.request.arguments)
        if user_form.validate():
            # 查数据
            try:
                string = user_form.password.data
                sha1 = hashlib.sha1()
                sha1.update(string.encode('utf-8'))
                password = sha1.hexdigest()
                user = await self.manager.get(User, username=user_form.username.data, password=password)
                payload = {
                    'username': user.username,
                    'exp': int(time.time()) + 60
                    # 86400 * 7
                }
                token = jwt.encode(payload, **JWT_SETTING)
                self.finish(to_dict_msg(code=200, msg='登录成功', token=token, username=user.username))
            except:
                # print("Unexpected error:", sys.exc_info()[0])
                self.finish(to_dict_msg(code=401, msg='用户名密码错误'))
        else:
            self.finish(to_dict_msg(code=401, msg='用户名密码不合法', **user_form.errors))


class GetUserHandler(BaseHandler):
    @login_require_async
    async def get(self):
        id = self._user_id
        try:
            # 有数据，将数据返回
            user = await self.manager.get(User, id=id)
            if user:
                self.finish(to_dict_msg(200, msg='查询用户数据成功', user=user.to_json()))
            else:
                self.finish(to_dict_msg(401, msg='非法用户'))
        except:
            self.finish(to_dict_msg(888, msg='数据库错误'))


class Test(BaseHandler):
    def get(self):
        token = self.request.headers.get('token')
        if token is not None:
            try:
                paylod = jwt.decode(token, JWT_SETTING['key'], [JWT_SETTING['algorithm']], options={'verify_exp': True},
                                    leeway=10)
                self.finish(to_dict_msg(200, msg=int(time.time()), data=paylod))
            except:
                self.finish(to_dict_msg(400, msg='token参数不合法或过期'))

        else:
            self.finish(to_dict_msg(403, msg='非法访问'))